import React, {FC, useCallback, useEffect, useMemo, useRef, useState} from "react";
import BaseForm from "../../../module/form/BaseForm.tsx";
import {getFormView} from "../../../services/ViewService.tsx";
import {Button, Dropdown, Table} from "antd";
import {useTranslation} from "react-i18next";
import GlobalIcon from "../../../global/GlobalIcon.tsx";
import {coreDispatch} from "../../../utils/StoreUtil.tsx";
import {getLanguageById} from "../../../../i18n/i18n.tsx";
import SelectModal from "../select/SelectModal.tsx";
import useStateRef from "../../../customUse/useStateRef.tsx";
import {addOkModal, closeModal} from "../../../services/ModalService.tsx";
import useThrottle from "../../../customUse/useThrottle.tsx";
import {AxiosSer} from "../../../services/HttpService.tsx";

interface CreateFlowNodeModalProps {
    modalKey: string,
    viewName: string,
    rowId: string,
    type: string,
    dataSource: any,
    flowData: any
}

const CreateFlowNodeModal: FC<CreateFlowNodeModalProps> = (props) => {
    const {viewName, dataSource = {}, flowData = {}} = props;

    const {t} = useTranslation();

    const fromRef = useRef(),
        listRef = useRef([]),
        columnsRef = useRef([
            {
                title: t("name"),
                dataIndex: "approverName"
            },
            {
                title: t("type"),
                dataIndex: "range"
            },
            {
                width: 50,
                title: t("opt"),
                dataIndex: "oper",
                render: (value, row, i) => {
                    return <Button icon={<GlobalIcon name="icon-delete"/>} size='small' onClick={() => {
                        let curIndex = listRef.current.findIndex((elem) => elem.approverId === row.approverId && elem.range === row.range);
                        if (curIndex !== -1) {
                            const newList = [...listRef.current];
                            newList.splice(curIndex, 1);
                            console.log(newList, "xxxxxxxxxxxx")
                            setList(newList);
                        }
                    }}/>
                }
            }
        ]);

    const [view, setView] = useState(undefined),
        [list, setList] = useStateRef([], listRef);

    const isCreate: Function = useCallback(() => {
        return props.type === "create";
    }, [props.type]);

    const isEdit: Function = useCallback(() => {
        return props.type === "edit";
    }, [props.type]);


    const loadData = useCallback(async () => {
        const editData = isEdit() ? {...flowData} : {};
        const result = await getFormView(viewName, {...editData}, dataSource);
        const {approverList = []} = editData;
        setView(result.form);
        setList(approverList.map(i => ({
            approverId: i.approverId,
            approverName: i.approverName,
            range: i.range
        })));
    }, [props.type, viewName]);


    useEffect(() => {
        loadData();
    }, [viewName]);

    const onOk = useThrottle(async () => {
        const values = await fromRef.current.validateFields();
        let params = {
            ...values,
            processId: props.rowId,
            approverList: listRef.current,
            index: isCreate() ? undefined : flowData.index
        }
        const methodType = isEdit() ? "PUT" : "POST";

        const result = (await AxiosSer("/sf-drs/platform/processNode", methodType, params, true)) || {};
        result.code == "1" && await closeModal(props.modalKey, async () => {
            return result;
        });
    }, 2000, [props.modalKey, props]);


    useEffect(() => {
        addOkModal(props.modalKey, onOk)
    }, []);


    const handleClick = useCallback(({key}) => {
        let comProps = {};
        switch (key) {
            case "User":
                comProps = {
                    isLazyData: true,
                    rowSelection: "multiple",
                    tableApi: {"url": "/sf-drs/platform/users", params: {status: "ACTIVE"}},
                    viewName: "col_user_list"
                }
                break;
            case "RoleInGroup":
                comProps = {
                    isTreeTable: true,
                    isLazyData: true,
                    rowKey: "seqID",
                    rowSelection: "multiple",
                    tableApi: {"url": "/sf-drs/platform/organizes/roles", params: {needDefaultGroup: false}},
                    viewName: "col_user_role_list",
                    isRowSelectable: (node) => {
                        const {data} = node, {attributes} = data;
                        return attributes.NTYPE === "GXRoleInGroup"
                    }
                }
                break;
            case "Group":
                comProps = {
                    isTreeTable: true,
                    isLazyData: true,
                    rowKey: "seqID",
                    rowSelection: "multiple",
                    tableApi: {
                        url: '/sf-drs/platform/groups',
                        params: {needDefaultGroup: false},
                        paramsRule: {"groupId": "id", "seqId": "seqID"},
                        hasChildrenKey: "attributes.hasChildren"
                    },
                    viewName: "col_user_group_list"
                }
                break;
        }
        coreDispatch("modalReducer/createModal", {
            key: `add-${key}-flow-node`,
            modalProps: {
                title: t(key),
                okText: getLanguageById("add"),
                cancelText: getLanguageById("cancel"),
                width: 800
            },
            component: SelectModal,
            comProps: {
                ...comProps
            },
            onFinish: (res: any) => {
                if (res && res.data) {
                    const {data = []} = res;
                    const addList = data
                        .filter(i => !listRef.current.find(n => n.approverId === i.id && n.range === key)).map(i => {
                            return {
                                approverId: i.id,
                                approverName: key === "User" ? `${i.name}(${i.lastName}${i.firstName})` : i.name,
                                range: key
                            }
                        })
                    setList([...listRef.current, ...addList])
                }
            }
        });
    }, []);


    const renderCreateFlowNodeTableTitle = useCallback(() => {
        return (
            <div>
                <Dropdown menu={{
                    items: [
                        {label: t("user"), key: "User"},
                        {label: t("role"), key: "RoleInGroup"},
                        {label: t("group"), key: "Group"}
                    ],
                    onClick: handleClick
                }}>
                    <Button>{t("addApproval")}<GlobalIcon name="icon-launch"/></Button>
                </Dropdown>
            </div>
        )
    }, [])


    const renderCreateFlowNodeModal = useMemo(() => {
        if (!view) {
            return null
        }
        return (
            <div className="sf_core_flow_node_create">
                <div className="sf_core_flow_node_create_form">
                    <BaseForm
                        init={fromRef}
                        view={view}
                        formItemLayout={1}
                    />
                </div>
                <div className="sf_core_flow_node_create_table">
                    <Table
                        dataSource={list}
                        columns={columnsRef.current}
                        pagination={false}
                        size='small'
                        bordered={true}
                        title={renderCreateFlowNodeTableTitle}
                    />
                </div>
            </div>
        )
    }, [view, list]);

    return (renderCreateFlowNodeModal);
};

export default React.memo(CreateFlowNodeModal);